<!--
 * @description  : 案件-投诉举报表单
 * @descriptionDetail: 案件-投诉举报表单
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-08-25 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
    </theme-navbar>
    <!-- #endif -->
    <view class="content complaint">
      <u-form
        :model="reportRecordForm"
        label-position="top"
        label-width="auto"
        :errorType="errorMsg"
        class="compform"
        ref="complainFormRef"
      >
        <u-form-item
          label-position="left"
          :required="true"
          label="举报时间"
          right-icon="arrow-right"
          prop="reportTime"
          class="row"
        >
          <u-picker
            :params="{
              year: true,
              month: true,
              day: true,
              hour: true,
              minute: true,
              second: false,
              timestamp: true, // 1.3.7版本提供
            }"
            v-model="isShowTime"
            @confirm="timeChange"
          ></u-picker>
          <u-input
            :disabled="true"
            placeholder="请选择举报时间"
            inputAlign="right"
            v-model="reportRecordForm.reportTime"
            @click="()=>{if(state.canEdit) isShowTime = true}"
          />
        </u-form-item>
        <u-form-item label-position="left" :required="true" label="举报形式" prop="reportType">
          <dic-input
            :keyWord="$u.dic.DIC_KEYS.REPORT_STYLE"
            :dicCode="reportRecordForm.reportType"
            :border="false"
            inputAlign="right"
            type="select"
            :select-open="dicSelectOpen('reason',$u.dic.DIC_KEYS.REPORT_STYLE)"
            placeholder="请选择举报形式"
            :disabled="true"
            v-model="reportRecordForm.reportTypeName"
            @changeInputModelData="(name)=>{$set(reportRecordForm, 'reportTypeName', name)}"
            @click="()=>{if(state.canEdit) showDic($u.dic.DIC_KEYS.REPORT_STYLE,reportRecordForm.reportType,'reportType')}"
          />
        </u-form-item>
        <u-form-item :required="true" label="举报人相关情况" prop="reportPersonDesc" class="row">
          <u-input
            class="over-height"
            maxlength="1000"
            type="textarea"
            :clearable="false"
            placeholder="请输入"
            :disabled="!state.canEdit"
            v-model="reportRecordForm.reportPersonDesc"
          />
        </u-form-item>
        <u-form-item :required="true" label="举报内容" prop="reportContent" class="row">
          <u-input
            class="over-height"
            maxlength="1000"
            type="textarea"
            :clearable="false"
            :disabled="!state.canEdit"
            placeholder="请输入"
            v-model="reportRecordForm.reportContent"
          />
        </u-form-item>
        <u-form-item
          :required="true"
          label="接待人"
          label-position="left"
          :arrow-right="true"
          class="row"
          prop="receptionPersonUuids"
        >
          <u-input
            type="select"
            readOnly
            :clearable="false"
            placeholder="请选择"
            inputAlign="right"
            v-model="reportRecordForm.receptionStaff"
            @click="()=>{if(state.canEdit) selectTaker()}"
          />
        </u-form-item>
        <u-form-item
          label-position="left"
          label="接待时间"
          right-icon="arrow-right"
          prop="receptionTime"
          class="row"
        >
          <u-calendar mode="date" max-date="2099-12-31" v-model="isShowTime1" @change="timeChange1">
          </u-calendar>
          <u-input
            :disabled="true"
            placeholder="请选择接待时间"
            inputAlign="right"
            v-model="reportRecordForm.receptionTime"
            @click="()=>{if(state.canEdit) isShowTime1 = true}"
          />
        </u-form-item>
        <u-form-item label="接待人意见" prop="receptionAdvice" class="row">
          <u-input
            class="over-height"
            maxlength="1000"
            type="textarea"
            :clearable="false"
            :disabled="!state.canEdit"
            placeholder="请输入"
            v-model="reportRecordForm.receptionAdvice"
          />
        </u-form-item>
        <u-form-item label="备注" prop="memo" class="row">
          <u-input
            class="over-height"
            maxlength="1000"
            type="textarea"
            :clearable="false"
            :disabled="!state.canEdit"
            placeholder="请输入"
            v-model="reportRecordForm.memo"
          />
        </u-form-item>
      </u-form>
    </view>
    <view class="submit-btns" v-show="!!state.canEdit">
      <u-button plain class="del" type="success" @click="submit(false)">
        保存
      </u-button>
      <u-button plain class="mit" type="primary" @click="submit(true)">
        提交
      </u-button>
    </view>
    <!-- 下拉选择用 -->
    <dic-choice
      :keyWord="dicKeyWords"
      :currentSelect="dicCurrentSelect"
      v-model="shapeShow"
      @confirm="selectDicConfirm"
    ></dic-choice>
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
  </view>
</template>

<script>
import {
  CASE_SOURCE,
  CASE_SOURCE_NAME,
} from '@/service/case/mapping/index.js';
import DicInput from "@/components/dic_input.vue";
import DicChoice from "@/components/dic_choice.vue";
import PersonSelection from "@/pages/case/components/personSelection.vue";
import caseService from "@/service/case/case.service";
import officeService from "@/service/case/office.service";
import caseCommon from "../caseCommonMixin.js";
export default {
  components: {
    DicInput,
    DicChoice,
    PersonSelection,
  },
  mixins: [caseCommon,],
  onLoad(opt) {
    this.caseParam = this.getRouteParam();
  },
  data() {
    return {
      errorMsg: ["message",],
      shapeShow: false, // 举报形式 select
      dicType: "",
      dicKeyWords: "",
      dicCurrentSelect: "",
      isShowTime: false, // 控制时间显示与隐藏弹框
      isShowTime1: false,
      personSelectShow: false,
      employeeList: [],
      personSelectFlag: 1, // 1 选择接待人  2 选择审批人
      tmpBean: undefined,
      tmpData: undefined,
      psParam: {},
      // 投诉举报表单
      reportRecordForm: {
        reportTime: "", // 举报日期
        reportType: "", // 举报方式
        reportTypeName: "",
        reportPersonDesc: "", // 举报人有关情况
        reportContent: "", // 举报内容
        receptionAdvice: "", // 接待人意见
        receptionPersonUuids: "",
        receptionStaff: "",
      },
      // 表单规则校验
      rules: {
        reportTime: [{
          required: true,
          message: "请选择举报时间",
          trigger: ["change",],
        },],
        reportStyle: [{
          required: true,
          message: "请填写举报形式",
          trigger: ["blur",],
        },],
        reportPersonDesc: [{
          required: true,
          message: "请填写举报人相关情况",
          trigger: ["blur",],
        },],
        reportContent: [{
          required: true,
          message: "请填写举报内容",
          trigger: ["blur",],
        },],
        receptionStaff: [{
          required: true,
          message: "请选择接待人",
          trigger: ["blur",],
        },],
      },
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.complainFormRef.setRules(this.rules)
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 准备数据
      if (this.caseParam.bizUuid) {
        caseService.getSourceDocIns(this.caseParam.bizUuid).then(res => {
          if (res.success) {
            this.caseParam.id = res.bean;
            this.initDocInfo();
          }
        });
      } else {
        this.initDocInfo();
      }
    },
    initDocInfo() {
      this.docStep((_doc) => {
        caseService.getReportRegistDoc(this.caseParam).then(res => {
          // 有2个元素 说明是添加类型的
          if (res.success && res.data.length == 2) {
            // 取第二个
            let rs = res.data[1];
            let employeeList = this.parseEmployee(rs, "receptionPersonUuids",
              "receptionStaff");
            rs.reportTime = !rs.reportTime ? this.$u.date(Date.now(),
              'yyyy年mm月dd日 hh时MM分') : rs.reportTime;
            rs.receptionTime = !rs.receptionTime ? this.$u.date(Date.now(),
              'yyyy年mm月dd日 hh时MM分') : rs.receptionTime;
            this.employeeList = [...employeeList,];
            for (let k in rs) {
              if (Object.prototype.hasOwnProperty.call(this.reportRecordForm, k)) {
                this.reportRecordForm[k] = rs[k];
              } else {
                this.$set(this.reportRecordForm, k, rs[k]);
              }
            }
          } else {
            let rs = res.data[0];
            this.employeeList = this.parseEmployee(rs, "receptionPersonUuids",
              "receptionStaff");
            // 说明已经有数据了
            for (let k in rs) {
              if (Object.prototype.hasOwnProperty.call(this.reportRecordForm, k)) {
                this.reportRecordForm[k] = rs[k];
              } else {
                this.$set(this.reportRecordForm, k, rs[k]);
              }
            }
          }
          this.$modal.hideLoading();
        });
      });
    },
    dicSelectOpen(type, keyWords) {
      if (type == this.dicType) {
        if (this.dicKeyWords == keyWords && this.shapeShow) {
          return true;
        }
        return false;
      }
    },
    showDic(key, cur, type) {
      if (this.shapeShow) return;
      this.dicKeyWords = key;
      this.dicCurrentSelect = cur;
      this.shapeShow = true;
      this.dicType = type;
    },
    /**
			 * @description 下拉选中确定事件，处理选中的结果绑定至数据
			 * @params e 选中的结果数据
			 */
    selectDicConfirm(e) {
      if (this.dicKeyWords == this.$u.dic.DIC_KEYS.REPORT_STYLE) { // 未办证原因
        this.reportRecordForm.reportTypeName = e[0].label;
        this.reportRecordForm.reportType = e[0].extra.bcbCode;
      }
    },
    // 选择时间
    timeChange(e) {
      this.reportRecordForm.reportTime = this.$u.date(e.timestamp, 'yyyy年mm月dd日 hh时MM分')
    },
    timeChange1(e) {
      this.reportRecordForm.receptionTime = e.result.replace('-', '年').replace('-', '月') + '日';
    },
    handlerChoosePerson(e) {
      this.personSelectShow = false;
      if (this.personSelectFlag == 1) {
        this.employeeList = [...e,];
        let tIds = [];
        let tNames = [];
        this.employeeList.forEach(el => {
          tIds.push(el.personUuid);
          tNames.push(el.personName);
        });
        this.reportRecordForm.receptionPersonUuids = tIds.join(",");
        this.reportRecordForm.receptionStaff = tNames.join(",");
      } else if (this.personSelectFlag == 2) {
        let nextP = [];
        e.forEach((item) => {
          nextP.push(item.personId);
        });
        this.$modal.showLoading('正在提交...');
        caseService.submitReportRegist(this.tmpBean, this.tmpData.docUuid, this.tmpData.docInsUuid, nextP.join(
          ','), "edit", this.tmpData.configIns.itemUuid).then(res => {
          this.$modal.hideLoading();
          if (res.success) {
            this.$modal.alert('提交成功', () => {
              this.backPrev({
                paramKey:"refreshBack",
                param: true,
              });
            });
          } else {
            this.$modal.alert('提交失败:' + res.msg);
          }
        }).catch(err => {
          this.$modal.hideLoading();
          this.$modal.alert('提交失败:' + err);
        });
      }
    },
    // 选择框 注意返回值为一个数组，单列时取数组的第一个元素即可(只有一个元素)
    selectConfirm(e) {
      let data = e[0];
      this.reportRecordForm.reportStyleName = data.label;
      this.reportRecordForm.reportStyle = data.value;
    },
    // 表单保存
    submit(flag) {
      let self = this;
      this.$refs.complainFormRef.validate(valid => {
        if (valid) {
          self.$modal.showLoading("保存中...");
          caseService.saveReportRegist(self.reportRecordForm, self.caseParam.docUuid).then(res => {
            if (res.success) {
              let bean = res.bean;
              let data = res.data[0];
              this.caseParam.id = bean.reportUuid;
              self.$modal.hideLoading();
              if (flag) {
                self.tmpBean = bean;
                self.tmpData = data;
                self.choseAuditPsr("docReportRecord");
              } else {
                this.$modal.alert('保存成功');
              }
            } else {
              self.$modal.hideLoading();
              self.$modal.alert("保存失败" + res.msg);
            }
          }).catch(err => {
            self.$modal.hideLoading();
            self.$modal.alert("保存失败" + err);
          });
        }
      })
    },
    selectTaker() {
      this.psParam = {
        min: 1,
        selectedPsrLst: [],
      };
      this.personSelectFlag = 1;
      this.personSelectShow = true;
    },
    choseAuditPsr(gfaCode) {
      this.personSelectFlag = 2;
      this.psParam = {
        min: 1,
        selectedPsrLst: [],
        dataHandler: (psrName) => {
          return caseService.getNextFlowUsers({
            page: 1,
            limit: 20,
            personName: psrName,
            gfCode: gfaCode,
          }).then(res => {
            if (res.success) {
              return res.data;
            } else {
              return [];
            }
          });
        },
      };
      this.personSelectShow = true;
    },
  },
}
</script>

<style lang="scss" scoped>
	.complaint {
		position: relative;
		width: 100%;
		line-height: 120rpx;
		padding: 0 48rpx 160rpx;

		.row {
			border-bottom: 2rpx solid $border-color-dark;
		}

		.source-title {
			display: flex;
			justify-content: space-between;

			.sub-title {
				font-family: "微软雅黑";
				font-size: 28rpx;
			}

			.strong {
				font-size: 30rpx;
				font-family: "微软雅黑";
				font-weight: Bold;
				color: $font-color-base;
			}
		}

		.over-height {
			overflow: hidden;
			height: 140rpx;
		}
	}

	.submit-btns {
		display: flex;
		position: fixed;
		bottom: 40rpx;
		left: 40rpx;
		right: 40rpx;
		text-align: center;

		.del {
			flex: 1;
		}

		.mit {
			flex: 1;
			margin-left: 40rpx;
		}
	}
</style>
